﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Windows.Forms;
using Castle.ActiveRecord.Framework.Config;
using CosyTrade.Core;
using CosyTrade.Data;
using Castle.ActiveRecord;

namespace CosyTrade.InternalServerUI
{
    public partial class Form1 : Form
    {
        public Form1(bool autoStart)
        {
            InitializeComponent();
            AutoStart = autoStart;
            Load += Form1_Load;
        }

        void Form1_Load(object sender, EventArgs e)
        {
            if (AutoStart) button1_Click(sender, e);
        }

        public bool AutoStart { get; set; }

        AddinServices services =null;

        private void button1_Click(object sender, EventArgs e)
        {
            if (services != null)
                services.StartAddin();
            else
            {
                services = AddinServices.Instance;
                services.InitalizeAddin();
                InitOrm();
                services.StartAddin();
            }
            listBox1.Items.Clear();
            IList<IAddin> runningAddin = services.AddinManager.GetAddinList();
            foreach (IAddin addin in runningAddin)
                listBox1.Items.Add(addin.AddinName + "... ... 加载成功！");
            listBox1.Items.Add("贸易行管理系统服务器正在运行中......");
            label1.Text = "服务运行状态：正在运行中... ...";
            button1.Enabled = false;
            button2.Enabled = true;
        }

        private void button2_Click(object sender, EventArgs e)
        {
            services.Stop();
            button1.Enabled = true;
            button2.Enabled = false;
            Close();
        }

        private static void InitOrm()
        {
            string defaultDbConfigPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "dbConfig.xml");
            XmlConfigurationSource source = new XmlConfigurationSource(defaultDbConfigPath);
            Type[] ormTypes = GetOrmTypes();
            OrmDataAccess.Initialize(source, ormTypes);
        }

        private static Type[] GetOrmTypes()
        {
            Assembly contractAssembly =
                Assembly.LoadFile(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "CosyTrade.Contract.dll"));
            Type[] assemblyTypes = contractAssembly.GetTypes();
            List<Type> ormTypes = new List<Type>();
            foreach (Type assemblyType in assemblyTypes)
            {
                if (!assemblyType.IsDefined(typeof(ActiveRecordAttribute), false)) continue;
                if (!assemblyType.IsDefined(typeof(SerializableAttribute), false))
                    throw new Exception(string.Format("{0} Not Mark SerializableAttribute", assemblyType.FullName));
                ormTypes.Add(Type.GetType(assemblyType.AssemblyQualifiedName));
            }
            return ormTypes.ToArray();
        }
    }
}
